import React, { forwardRef, useRef, useEffect } from 'react';

export interface BarChartDataItem {
  name: string;
  value: number;
  category?: string;
}

export interface MultiBarChartProps {
  /**
   * 图表标题
   */
  title?: string;

  /**
   * X轴字段数据
   */
  xAxisData?: string[];

  /**
   * Y轴数据系列
   */
  yAxisData?: BarChartDataItem[][];

  /**
   * 柱状图类型
   */
  chartType?: 'grouped' | 'stacked';

  /**
   * 宽度
   */
  width?: string | number;

  /**
   * 高度
   */
  height?: string | number;

  /**
   * 柱体宽度
   */
  barWidth?: number;

  /**
   * 颜色配置
   */
  colors?: string[];

  /**
   * X轴标签旋转角度
   */
  xAxisLabelRotation?: number;

  /**
   * X轴显示间隔
   */
  xAxisInterval?: number;

  /**
   * Y轴单位文本
   */
  yAxisUnit?: string;

  /**
   * Y轴刻度间隔
   */
  yAxisInterval?: number;

  /**
   * 显示图例
   */
  showLegend?: boolean;

  /**
   * 图例位置
   */
  legendPosition?: 'top' | 'bottom' | 'left' | 'right';

  /**
   * 图例颜色
   */
  legendColor?: string;

  /**
   * 显示数值
   */
  showValues?: boolean;

  /**
   * 标签位置
   */
  labelPosition?: 'top' | 'inside' | 'center';

  /**
   * 点击事件
   */
  onClick?: (item?: BarChartDataItem, index?: number) => void;

  /**
   * 自定义样式
   */
  style?: React.CSSProperties;

  /**
   * 自定义类名
   */
  className?: string;

  /**
   * 设计模式标识
   */
  __designMode?: string;

  /**
   * 组件ID
   */
  componentId?: string;

  /**
   * forwardRef属性
   */
  forwardRef?: any;
}

const MultiBarChart = forwardRef<HTMLDivElement, MultiBarChartProps>((props, ref) => {
  const {
    title = '小时运力图',
    xAxisData = ['供配电', '给排水', '消防', '暖通'],
    yAxisData = [
      [
        { name: '正常', value: 48, category: '正常' },
        { name: '正常', value: 20, category: '正常' },
        { name: '正常', value: 15, category: '正常' },
        { name: '正常', value: 48, category: '正常' }
      ],
      [
        { name: '告警', value: 8, category: '告警' },
        { name: '告警', value: 1, category: '告警' },
        { name: '告警', value: 1, category: '告警' },
        { name: '告警', value: 12, category: '告警' }
      ]
    ],
    chartType = 'grouped',
    width = 400,
    height = 300,
    barWidth = 0.8,
    colors = ['#5AF3B8', '#FF6B6B'],
    xAxisLabelRotation = 0,
    xAxisInterval = 1,
    yAxisUnit = '(个)',
    yAxisInterval = 10,
    showLegend = true,
    legendPosition = 'top',
    legendColor = '#FFFFFF',
    showValues = true,
    labelPosition = 'top',
    onClick,
    style = {},
    className = '',
    __designMode,
    componentId,
    forwardRef: forwardRefProp,
    ...otherProps
  } = props;

  const canvasRef = useRef<HTMLCanvasElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // 计算容器样式
  const containerStyle: React.CSSProperties = {
    ...style,
    width: typeof width === 'number' ? `${width}px` : width,
    height: typeof height === 'number' ? `${height}px` : height,
  };

  // 合并类名
  const classNames = [
    'hzdz-multi-bar-chart',
    className
  ].filter(Boolean).join(' ');

  // 处理点击事件
  const handleClick = (item?: BarChartDataItem, index?: number) => {
    if (onClick) {
      onClick(item, index);
    }
  };

  // 绘制图表
  useEffect(() => {
    const canvas = canvasRef.current;
    const container = containerRef.current;
    if (!canvas || !container) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const drawChart = () => {
      // 设置画布尺寸
      const rect = container.getBoundingClientRect();
      const dpr = window.devicePixelRatio || 1;
      
      canvas.width = rect.width * dpr;
      canvas.height = rect.height * dpr;
      canvas.style.width = `${rect.width}px`;
      canvas.style.height = `${rect.height}px`;
      
      ctx.scale(dpr, dpr);

      // 清空画布
      ctx.clearRect(0, 0, rect.width, rect.height);

      // 计算绘图区域
      const padding = { top: 60, right: 40, bottom: 80, left: 60 };
      const chartWidth = rect.width - padding.left - padding.right;
      const chartHeight = rect.height - padding.top - padding.bottom;

      // 计算数据最大值
      const allValues = yAxisData.flat().map(item => item.value);
      const maxValue = Math.max(...allValues);
      const yMax = Math.ceil(maxValue / yAxisInterval) * yAxisInterval;

      // 绘制Y轴
      ctx.strokeStyle = '#333333';
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(padding.left, padding.top);
      ctx.lineTo(padding.left, padding.top + chartHeight);
      ctx.stroke();

      // 绘制Y轴刻度和标签
      ctx.fillStyle = '#999999';
      ctx.font = '12px SourceHanSansSC';
      ctx.textAlign = 'right';
      ctx.textBaseline = 'middle';

      for (let i = 0; i <= yMax; i += yAxisInterval) {
        const y = padding.top + chartHeight - (i / yMax) * chartHeight;
        
        // 刻度线
        ctx.beginPath();
        ctx.moveTo(padding.left - 5, y);
        ctx.lineTo(padding.left, y);
        ctx.stroke();

        // 标签
        ctx.fillText(i.toString(), padding.left - 10, y);

        // 网格线
        if (i > 0) {
          ctx.strokeStyle = '#f0f0f0';
          ctx.beginPath();
          ctx.moveTo(padding.left, y);
          ctx.lineTo(padding.left + chartWidth, y);
          ctx.stroke();
          ctx.strokeStyle = '#333333';
        }
      }

      // Y轴单位
      ctx.fillStyle = '#999999';
      ctx.font = '12px SourceHanSansSC';
      ctx.textAlign = 'center';
      ctx.fillText(yAxisUnit, padding.left - 30, padding.top - 10);

      // 绘制X轴
      ctx.beginPath();
      ctx.moveTo(padding.left, padding.top + chartHeight);
      ctx.lineTo(padding.left + chartWidth, padding.top + chartHeight);
      ctx.stroke();

      // 计算柱子参数
      const categoryCount = xAxisData.length;
      const seriesCount = yAxisData.length;
      const categoryWidth = chartWidth / categoryCount;
      const actualBarWidth = categoryWidth * barWidth;

      // 绘制柱子
      xAxisData.forEach((category, categoryIndex) => {
        const categoryX = padding.left + categoryIndex * categoryWidth;
        
        if (chartType === 'grouped') {
          // 并列柱状图
          const barWidthPerSeries = actualBarWidth / seriesCount;
          const startX = categoryX + (categoryWidth - actualBarWidth) / 2;

          yAxisData.forEach((series, seriesIndex) => {
            const item = series[categoryIndex];
            if (!item) return;

            const barX = startX + seriesIndex * barWidthPerSeries;
            const barHeight = (item.value / yMax) * chartHeight;
            const barY = padding.top + chartHeight - barHeight;

            // 绘制柱子
            ctx.fillStyle = colors[seriesIndex % colors.length];
            ctx.fillRect(barX, barY, barWidthPerSeries, barHeight);

            // 绘制数值标签
            if (showValues) {
              ctx.fillStyle = '#FFFFFF';
              ctx.font = '12px SourceHanSansSC';
              ctx.textAlign = 'center';
              ctx.textBaseline = 'bottom';
              
              let labelY = barY - 5;
              if (labelPosition === 'inside') {
                labelY = barY + barHeight / 2;
                ctx.textBaseline = 'middle';
              } else if (labelPosition === 'center') {
                labelY = barY + barHeight / 2;
                ctx.textBaseline = 'middle';
              }
              
              ctx.fillText(item.value.toString(), barX + barWidthPerSeries / 2, labelY);
            }
          });
        } else {
          // 堆叠柱状图
          const barX = categoryX + (categoryWidth - actualBarWidth) / 2;
          let stackY = padding.top + chartHeight;

          yAxisData.forEach((series, seriesIndex) => {
            const item = series[categoryIndex];
            if (!item) return;

            const barHeight = (item.value / yMax) * chartHeight;
            stackY -= barHeight;

            // 绘制柱子
            ctx.fillStyle = colors[seriesIndex % colors.length];
            ctx.fillRect(barX, stackY, actualBarWidth, barHeight);

            // 绘制数值标签
            if (showValues) {
              ctx.fillStyle = '#FFFFFF';
              ctx.font = '12px SourceHanSansSC';
              ctx.textAlign = 'center';
              ctx.textBaseline = 'middle';
              
              ctx.fillText(item.value.toString(), barX + actualBarWidth / 2, stackY + barHeight / 2);
            }
          });
        }

        // 绘制X轴标签
        const shouldShowLabel = categoryIndex % xAxisInterval === 0;
        if (shouldShowLabel) {
          ctx.fillStyle = '#999999';
          ctx.font = '12px SourceHanSansSC';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'top';
          
          const labelX = categoryX + categoryWidth / 2;
          const labelY = padding.top + chartHeight + 10;
          
          if (xAxisLabelRotation !== 0) {
            ctx.save();
            ctx.translate(labelX, labelY);
            ctx.rotate((xAxisLabelRotation * Math.PI) / 180);
            ctx.fillText(category, 0, 0);
            ctx.restore();
          } else {
            ctx.fillText(category, labelX, labelY);
          }
        }
      });

      // 绘制图例
      if (showLegend && yAxisData.length > 0) {
        const legendItems = ['正常', '告警'];
        const legendItemWidth = 80;
        const legendHeight = 20;
        
        let legendX: number, legendY: number;
        
        switch (legendPosition) {
          case 'top':
            legendX = (rect.width - legendItems.length * legendItemWidth) / 2;
            legendY = 10;
            break;
          case 'bottom':
            legendX = (rect.width - legendItems.length * legendItemWidth) / 2;
            legendY = rect.height - 30;
            break;
          case 'left':
            legendX = 10;
            legendY = (rect.height - legendItems.length * legendHeight) / 2;
            break;
          case 'right':
            legendX = rect.width - 100;
            legendY = (rect.height - legendItems.length * legendHeight) / 2;
            break;
          default:
            legendX = (rect.width - legendItems.length * legendItemWidth) / 2;
            legendY = 10;
        }

        legendItems.forEach((item, index) => {
          const itemX = legendPosition === 'left' || legendPosition === 'right' 
            ? legendX 
            : legendX + index * legendItemWidth;
          const itemY = legendPosition === 'left' || legendPosition === 'right'
            ? legendY + index * legendHeight
            : legendY;

          // 绘制色块
          ctx.fillStyle = colors[index % colors.length];
          ctx.fillRect(itemX, itemY, 12, 12);

          // 绘制文字
          ctx.fillStyle = legendColor;
          ctx.font = '12px SourceHanSansSC';
          ctx.textAlign = 'left';
          ctx.textBaseline = 'middle';
          ctx.fillText(item, itemX + 18, itemY + 6);
        });
      }

      // 绘制标题
      if (title) {
        ctx.fillStyle = '#FFFFFF';
        ctx.font = 'bold 16px SourceHanSansSC';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'top';
        ctx.fillText(title, rect.width / 2, 20);
      }
    };

    // 延迟绘制以确保DOM完全加载
    const timer = setTimeout(() => {
      drawChart();
    }, 100);

    // 窗口大小改变时重新绘制
    const handleResize = () => {
      drawChart();
    };

    window.addEventListener('resize', handleResize);

    return () => {
      clearTimeout(timer);
      window.removeEventListener('resize', handleResize);
    };
  }, [
    title, xAxisData, yAxisData, chartType, width, height, barWidth, colors,
    xAxisLabelRotation, xAxisInterval, yAxisUnit, yAxisInterval,
    showLegend, legendPosition, legendColor, showValues, labelPosition
  ]);

  return React.createElement('div', {
    ref: containerRef,
    className: classNames,
    style: containerStyle,
    onClick: () => handleClick(),
    ...otherProps
  }, [
    // 设计模式提示
    __designMode && React.createElement('div', {
      key: 'design-mode-tip',
      className: 'hzdz-multi-bar-chart__design-tip'
    }, '多系列柱状图'),

    // Canvas画布
    React.createElement('canvas', {
      key: 'canvas',
      ref: canvasRef,
      className: 'hzdz-multi-bar-chart__canvas'
    })
  ]);
});

MultiBarChart.displayName = 'MultiBarChart';

export default MultiBarChart; 